package com.nj.dms.controller;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.nj.dms.bean.User;
import com.nj.dms.dao.UserDao;
import com.nj.dms.dao.impl.UserDaoImpl;

/**
 * 修改密码
 */
@WebServlet("/UpdatePassword")
public class UpdatePassword extends HttpServlet {
	private static final long serialVersionUID = 1L;

	protected void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		String passwordOld = request.getParameter("password-old");
		String passwordNew_1 = request.getParameter("password-new-1");
		String passwordNew_2 = request.getParameter("password-new-2");

		request.setAttribute("passwordOld", passwordOld);
		request.setAttribute("passwordNew_1", passwordNew_1);
		request.setAttribute("passwordNew_2", passwordNew_2);

		boolean flag = true;

		if (!passwordNew_1.equals(passwordNew_2)) {
			flag = false;

			request.setAttribute("passwordErr_2", "两次输入的密码不一致");

		}

		UserDao userDao = new UserDaoImpl();

		User user = new User();

		HttpSession session = request.getSession();

		String userName = (String) session.getAttribute("userName");
		int type = (int) session.getAttribute("type");

		user.setUserName(userName);
		user.setPassword(passwordOld);
		user.setType(type);

		System.out.println(userName);
		System.out.println(passwordOld);

		if (!userDao.findUserByLogin(user)) {
			flag = false;
			request.setAttribute("passwordErr_1", "密码输入错误");
		}

		if (flag) {

			if (userDao.updatePassword(userName, passwordNew_1)) {

				// 密码修改成功

				response.sendRedirect("document/my-document-menu.jsp");

			} else {

				// 修改失败
				request.setAttribute("passwordErr_2", "密码修改失败");

				request.getRequestDispatcher("user/update-password.jsp").forward(request, response);

			}

		} else {

			// 数据效验未通过

			request.getRequestDispatcher("user/update-password.jsp").forward(request, response);
		}

	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		doGet(request, response);
	}

}
